// 1. jq的入口函数，当页面的dom树创建完成时使用
$(function() {
    // 2. 请求当前用户信息接口
    getUserinfo();
    $('#btnLogout').on('click', logout)
})

function getUserinfo() {
    $.ajax({
        url: '/my/userinfo',
        // method:'get',
        // 向请求头中添加token
        headers: {
            Authorization: localStorage.getItem('token')
        },
        success(res) {
            // a.提示信息
            layui.layer.msg(res.message)
            if (res.status !== 0) {
                return
            }
            ranDom(res.data)
        }
    })
}

function ranDom(usrInfo) {
    const usrName = usrInfo.nickname || usrInfo.username
    $('#usrName').text(usrName)
    if (usrInfo.user_pic) {
        $('.img-avatar').attr('src', usrInfo.user_pic).show()
        $('.text-avatar').hide()
    } else {

        $('.text-avatar').text(usrName[0].toUpperCase()).show()
        $('.img-avatar').hide()
    }
}

function logout(e) {
    e.preventDefault();
    layui.layer.confirm('你确定退出吗？', { icon: 3, title: '确定么' }, function(index) {
        localStorage.removeItem('token')
        location.href = '/login.html'
    })
}